<template>
  <page-detail ref="page" background-color="#f6f6f6" :title="pageTitle">
    <div class="chat-container" id="scroll-view-content">
      <div
        :id="`message${index}`"
        v-for="(message, index) in messages"
        :key="message.id"
      >
        <div v-if="shouldShowTimestamp(index)" class="timestamp">
          {{ fmtTime(message.createTime) }}
        </div>
        <im-message :avatarUrl="avatarUrl" :message="message" />
      </div>
    </div>
    <template #footer>
      <div style="flex: 1; display: flex; align-items: center; gap: 10px">
        <van-field
          v-model="messageValue"
          placeholder="输入消息"
          style="border: 1px solid #efefef"
        />
        <ne-file-upload @change="fileChange" :max-file="1" v-model="files">
          <van-button icon="photo" type="primary" />
        </ne-file-upload>
        <van-button
          style="width: 100px; flex: auto"
          type="primary"
          :disabled="!messageValue"
          @click="sendMessage"
          >发送</van-button
        >
      </div>
    </template>
  </page-detail>
</template>

<script>
import imMessage from './components/im-message.vue'
import WebSocketService from '../../utils/WebSocketClient'
import { mapGetters } from 'vuex'
import { tbChatMessageHistory } from '../../api/tbChatMessage'
import dayjs from 'dayjs'
import moment from 'moment'
import NeFileUpload from '../../components/NeFileUpload.vue'

function isEmpty(str) {
  return `${str}` === 'undefined' || `${str}` === 'null'
}
export default {
  name: 'wx_pages_consult_consultIm',
  components: {
    NeFileUpload,
    imMessage,
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  data() {
    return {
      wsService: null,
      messageValue: '',
      receiver: '',
      messages: [],
      files: [],
      pageTitle: '',
      avatarUrl: '',
    }
  },
  beforeDestroy() {
    if (this.wsService) {
      this.wsService.close()
      this.wsService = null
    }
  },
  methods: {
    shouldShowTimestamp(index) {
      if (index === 0) return true

      // 使用 Moment.js 解析日期
      const currentMessageTime = moment(
        this.messages[index].createTime,
        'YYYY-MM-DD HH:mm:ss'
      )
      const previousMessageTime = moment(
        this.messages[index - 1].createTime,
        'YYYY-MM-DD HH:mm:ss'
      )

      // 检查日期是否有效
      if (!currentMessageTime.isValid() || !previousMessageTime.isValid()) {
        console.error(
          '无效的日期格式:',
          this.messages[index].createTime,
          this.messages[index - 1].createTime
        )
        return false // 或者根据需要处理无效日期
      }

      // 计算时间差（以秒为单位）
      const timeDifference = currentMessageTime.diff(
        previousMessageTime,
        'seconds'
      )

      // 如果时间差小于 60 秒，则不显示时间戳
      return timeDifference >= 60
    },
    async search() {
      let res = await tbChatMessageHistory({
        userId: this.userInfo.userId,
        contactUserId: this.receiver,
      })
      if (res && res.length) {
        this.messages = res.sort((a, b) => {
          return moment(a.createTime).diff(moment(b.createTime))
        })
        this.$refs.page.scrollToBottom()
      }
    },
    connect(receiver) {
      const self = this
      this.wsService = new WebSocketService(
        `${process.env.VUE_APP_WS_URL}?userId=${encodeURIComponent(
          this.userInfo.userId
        )}`
      )
      this.wsService.onMessage((msg) => {
        if (msg.receiver === self.userInfo.userId && msg.sender === receiver) {
          console.log('msg', msg)
          self.messages.push(msg)
          console.log('scrollToBottom')
          self.scrollToBottom()
        }
      })
    },
    fileChange() {
      this.sendMessage()
    },
    sendMessage() {
      const { receiver } = this.$route.query
      const message = {
        receiver: receiver,
        type: 'text',
        sender: this.userInfo.userId,
        content: this.messageValue,
        createTime: moment().format(`yyyy-MM-DDTHH:mm:ss.SSSZ`),
      }

      if (this.files.length) {
        message.type = 'file'
        message.content = JSON.stringify({
          fileName: this.files[0].name,
          fileType: this.files[0].type,
          fileUrl: this.files[0].url,
        })
      }
      this.wsService.sendMessage(message)
      this.messages.push(message)
      this.scrollToBottom()
      this.messageValue = ''
      this.files = []
    },
    scrollToBottom() {
      this.$refs.page.scrollToBottom()
    },
    fmtTime(time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm')
    },
  },
  mounted() {},
  watch: {
    userInfo: {
      immediate: true,
      deep: true,
      handler(userInfo) {
        if (userInfo && userInfo.userId) {
          this.receiver = this.$route.query.receiver
          this.search()
          this.pageTitle = this.$route.query.personName
          this.avatarUrl = this.$route.query.avatarUrl
          document.title = isEmpty(this.pageTitle) ? '咨询' : this.pageTitle
          this.connect(this.receiver)
        }
      },
    },
  },
  onLoad(query) {},
}
</script>

<style scoped>
.chat-container {
  padding: 20px;
  .timestamp {
    width: fit-content;
    text-align: center;
    background: #dddddd;
    margin: 16px auto;
    padding: 4px 18px;
    border-radius: 10px;
    color: #666666;
  }
}
</style>
